package com.sdy.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.mysql.jdbc.StringUtils;
import com.sdy.config.Constant;
import com.sdy.dto.EmployerDto;
import com.sdy.interceptor.AccessInterceptor;
import com.sdy.model.Department;
import com.sdy.model.Employer;
import com.sdy.model.Modeinfo;
import com.sdy.util.AjaxDone;
import com.sdy.util.HttpUtil;

public class EmployerController extends Controller {

	private Employer empdao = Employer.dao;
	private Modeinfo modInfoDao = Modeinfo.dao;
	private Department deptDao = Department.dao;

	public void index() {
		render("/admin/login.jsp");
	}

	public void login() {
		String username = getPara("username");
		String password = getPara("password");
		Employer emp = empdao.login(username, password);
		if (emp != null) {
			//登陆测试+1
			if(emp.getInt("loginTimes") == null) {
				emp.set("loginTimes", 1);
			} else {
				emp.set("loginTimes", emp.getInt("loginTimes") + 1);
			}
			//更新最后一次登陆时间
			emp.set("lastLoginDate", new Date());
			//更新登陆ip
			emp.set("ip", HttpUtil.getIpAddr(getRequest()));
			//更新emp信息
			emp.update();
			setSessionAttr("username", emp.get("username"));
			setSessionAttr("name",emp.get("name"));
			renderText("yes");
		} else {
			renderText("no");
		}
	}

	public void logSuccess() {
		render("/admin/index.jsp");
	}

	public void logout() {
		removeSessionAttr("username");
		redirect("/admin");
	}

	public void datagrid() {
		AjaxDone j = new AjaxDone();
		try {
			renderJson(empdao.datagrid(getParaToInt("page"),
					getParaToInt("rows")));
		} catch (Exception e) {
			j.setErrorMsg(e.getMessage());
			renderJson(j);
		}
	}

	@Before({Tx.class,AccessInterceptor.class})
	public void doAdd() {
		AjaxDone j = new AjaxDone();
		try {
			List<UploadFile> files = getFiles();
			Employer employer = getModel(Employer.class);
			String empId = employer.getStr("empId");
			String username = employer.getStr("username");
			if (StringUtils.isEmptyOrWhitespaceOnly(empId)) {
				throw new IllegalArgumentException("员工编号不能为空!");
			} else {
				if (StringUtils.isNullOrEmpty(username)) {
					throw new IllegalArgumentException("用户名不能为空!");
				} else {
					// 检查empId是否已经存在
					List<Employer> list = empdao.find(
							"select * from employer where empId = ?", empId);
					if (list != null && list.size() > 0) {
						throw new RuntimeException("该员工编号已经存在，请重新输入!");
					}
					list = empdao.find(
							"select * from employer where username = ?",
							username);
					if (list != null && list.size() > 0) {
						throw new RuntimeException("该用户名已经存在，请重新输入!");
					}
					if (files.size() != 2) {
						throw new RuntimeException("请上传两张图片!");
					} else {
						// 保存头像
						Modeinfo headImg = Modeinfo.dao
								.findFirst(
										"select * from modelinfo where owner = ? and seat = ?",
										empId, "headImg");
						if (headImg == null) {
							headImg = new Modeinfo();
							headImg.set("owner", empId);
							headImg.set("seat", "headImg");
						}
						headImg.set("dataType", Constant.img);
						String filePath = files.get(0).getSaveDirectory();
						String fileName = UUID.randomUUID().toString()+"."+files.get(0).getOriginalFileName().split("\\.")[1];
						files.get(0).getFile().renameTo(new File(filePath+"/"+fileName));
						headImg.set("picUrl", "/upload/"+fileName);
						if (!headImg.save()) {
							throw new RuntimeException("保存员工头像时发生异常!");
						}
						// 保存大头像
						Modeinfo bigImg = Modeinfo.dao
								.findFirst(
										"select * from modelinfo where owner = ? and seat = ?",
										empId, "bigImg");
						if (bigImg == null) {
							bigImg = new Modeinfo();
							bigImg.set("owner", empId);
							bigImg.set("seat", "bigImg");
						}
						bigImg.set("dataType", Constant.img);
						filePath = files.get(1).getSaveDirectory();
						fileName = UUID.randomUUID().toString()+"."+files.get(1).getOriginalFileName().split("\\.")[1];
						files.get(1).getFile().renameTo(new File(filePath+"/"+fileName));
						bigImg.set("picUrl", "/upload/" + fileName);
						// 保存员工介绍
						String info = getPara("info");
						if (!StringUtils.isNullOrEmpty(info)) {
							Modeinfo empInfo = new Modeinfo();
							empInfo.set("owner", empId);
							empInfo.set("seat", "info");
							empInfo.set("dataType", Constant.text);
							empInfo.set("textValue", info);
							if (!empInfo.save()) {
								throw new RuntimeException("保存员工介绍时发生异常!");
							}
						}
						if (!bigImg.save()) {
							throw new RuntimeException("保存员工大图时发生异常!");
						}
					}
				}
			}
			if (!employer.save())
				throw new RuntimeException("保存员工信息时发生异常!");
		} catch (Exception e) {
			e.printStackTrace();
			j.setErrorMsg(e.getMessage());
		}
		renderJson(j);
	}

	/**
	 * 删除员工信息
	 */
	@Before({Tx.class,AccessInterceptor.class})
	public void doDelete() {
		AjaxDone j = new AjaxDone();
		try {
			// 先删除与该员工相关的内容
			Employer employer = empdao.findById(getParaToInt("id"));
			// 判断其是不是管理员
			if (employer.getStr("username").equals("admin")) {
				throw new IllegalArgumentException("管理员无法被删除!");
			} else {
				modInfoDao.batchDeleteModeByOwner(employer.getStr("empId"));
				// 再删除员工信息
				employer.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
			j.setErrorMsg(e.getMessage());
		}
		renderJson(j);
	}

	/**
	 * 获取修改员工信息
	 * */
	public void goUpdate() {
		AjaxDone j = new AjaxDone();
		try {
			int id = getParaToInt("id");
			renderJson(empdao.getById(id));
		} catch (Exception e) {
			e.printStackTrace();
			j.setErrorMsg(e.getMessage());
			renderJson(j);
		}
	}

	/**
	 * 修改员工信息
	 * */
	@Before({Tx.class,AccessInterceptor.class})
	public void doUpdate() {
		AjaxDone j = new AjaxDone();
		try {
			List<UploadFile> files = getFiles();
			Employer employer = getModel(Employer.class);
			String empId = employer.getStr("empId");
			int empPriKey = employer.getInt("id");
			String username = employer.getStr("username");
			if (StringUtils.isEmptyOrWhitespaceOnly(empId)) {
				throw new IllegalArgumentException("员工编号不能为空!");
			} else {
				if (StringUtils.isNullOrEmpty(username)) {
					throw new IllegalArgumentException("用户名不能为空!");
				} else if (empPriKey == 0) {
					throw new IllegalArgumentException("前台参数异常!");
				}else {
					// 检查empId是否已经存在
					List<Employer> list = empdao
							.find("select * from employer where empId = ? and id <> ?",
									empId, empPriKey);
					if (list != null && list.size() > 0) {
						throw new RuntimeException("该员工编号已经存在，请重新输入!");
					}
					list = empdao.find(
							"select * from employer where username = ? and id <> ?",
							username, empPriKey);
					if (list != null && list.size() > 0) {
						throw new RuntimeException("该用户名已经存在，请重新输入!");
					}
					if (!employer.update()) {
						throw new RuntimeException("更新员工信息失败!");
					}
					Modeinfo headImg = getModel(Modeinfo.class, "headImg");
					Modeinfo bigImg = getModel(Modeinfo.class, "bigImg");
					//如果files的size为2
					if(files.size() == 2) {
						String filePath = files.get(1).getSaveDirectory();
						String fileName = UUID.randomUUID().toString()+"."+files.get(1).getOriginalFileName().split("\\.")[1];
						files.get(1).getFile().renameTo(new File(filePath+"/"+fileName));
						headImg.set("picUrl", "/upload/"+fileName);
						headImg.set("owner", employer.getStr("empId"));
						
						filePath = files.get(0).getSaveDirectory();
						fileName = UUID.randomUUID().toString()+"."+files.get(0).getOriginalFileName().split("\\.")[1];
						files.get(0).getFile().renameTo(new File(filePath+"/"+fileName));
						bigImg.set("picUrl", "/upload/" + fileName);
					} else if (files.size() == 1) {
						//谁的picUrl为空，即为对应的上传
						if(StringUtils.isNullOrEmpty(headImg.getStr("picUrl"))){
							String filePath = files.get(0).getSaveDirectory();
							String fileName = UUID.randomUUID().toString()+"."+files.get(0).getOriginalFileName().split("\\.")[1];
							files.get(0).getFile().renameTo(new File(filePath+"/"+fileName));
							headImg.set("picUrl", "/upload/"+fileName);
							headImg.set("owner", employer.getStr("empId"));
						} else if (StringUtils.isNullOrEmpty(bigImg.getStr("picUrl"))) {
							String filePath = files.get(0).getSaveDirectory();
							String fileName = UUID.randomUUID().toString()+"."+files.get(0).getOriginalFileName().split("\\.")[1];
							files.get(0).getFile().renameTo(new File(filePath+"/"+fileName));
							bigImg.set("picUrl", "/upload/" + fileName);
							bigImg.set("owner", employer.getStr("empId"));
						}
					} 
					
					
					if (!headImg.update()) {
						throw new RuntimeException("更新员工头像失败!");
					}
					
					if (!bigImg.update()) {
						throw new RuntimeException("更新员工大图失败!");
					}
					Modeinfo info = getModel(Modeinfo.class, "info");
					info.set("textValue", getPara("info"));
					info.set("owner", employer.getStr("empId"));
					if (!info.update()) {
						throw new RuntimeException("更新员工介绍失败!");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			j.setErrorMsg(e.getMessage());
		}
		renderJson(j);
	}
	
	public void show(){
		AjaxDone j = new AjaxDone();
		try {
			List<EmployerDto> dtoList = new ArrayList<EmployerDto>();
			List<Department> deptList = deptDao.find("select * from department");
			for (Department department : deptList) {
				EmployerDto dto = new EmployerDto();
				dto.setDepartmentName(department.getStr("name"));
				dto.setEmployerList(empdao.searchEmployerDtoByDeptId(department.getInt("id")));
				if(dto.getEmployerList().size()>0)
					dtoList.add(dto);
			}
			setAttr("empList", dtoList);
			render("../employer.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			j.setErrorMsg(e.getMessage());
			renderJson(j);
		}
	}
	
	/**
	 * 修改密码
	 * */
	@Before({AccessInterceptor.class})
	public void doUpdatePassword(){
		AjaxDone j = new AjaxDone();
		try {
			Employer emp = empdao.findById(getParaToInt("updatePasswordId"));
			emp.set("password",getPara("password1"));
			emp.set("isAdmin", getParaToInt("isAdmin"));
			emp.update();
		} catch (Exception e) {
			j.setErrorMsg(e.getMessage());
			e.printStackTrace();
		}
		renderJson(j);
	}
}
